import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/components/Layout/index.vue'
import { usePermissionStore } from '@/stores/permission'
import type { PermissionItemType } from '@/types/api/permission'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/Login/index.vue'),
      meta: {
        desc: '登录',
        isPublic: true
      }
    },
    {
      path: '/',
      name: 'home',
      component: Layout,
      children: [
        {
          path: '/',
          component: () => import('@/views/Home/index.vue'),
          meta: {
            desc: '首页',
            isPublic: true
          }
        }
      ]
    },
    {
      path: '/404',
      component: () => import('@/views/404/index.vue'),
      meta: {
        desc: '找不到页面',
        isPublic: true
      }
    }
  ]
})

router.beforeEach((to, from, next) => {
  const permissionStore = usePermissionStore()

  const title = to.meta.desc as string
  title && (document.title = title)

  let raf = 0
  const checkIsGetPermission = () => {
    if (permissionStore.permission.length > 0) {
      raf && cancelAnimationFrame(raf)
      next(to.path)
    } else {
      raf = requestAnimationFrame(checkIsGetPermission)
    }
  }

  const isPublic = to.meta.isPublic as boolean
  if (isPublic || permissionStore.permission.length > 0) {
    next()
  } else {
    checkIsGetPermission()
  }
})

router.afterEach((to, from, next) => {
  const permissionStore = usePermissionStore()
  const permission = permissionStore.permission
  const currentPermission = getCurrentPermission(to.path, permission)
  permissionStore.setCurrentPermission(currentPermission)
})

const getCurrentPermission = (
  target: string,
  permissions: PermissionItemType[]
): PermissionItemType | null => {
  for (const permission of permissions) {
    const { path, children } = permission
    if (path === target) {
      return permission
    } else {
      const ret = getCurrentPermission(target, children)
      if (ret) {
        return ret
      }
    }
  }
  return null
}

export default router
